package com.ruoyi.wms.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.wms.domain.WmsOwnerOrderNumberRule;
import com.ruoyi.wms.service.IWmsOwnerOrderNumberRuleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.wms.service.IWmsCargoOwnerService;
import com.ruoyi.wms.domain.WmsCargoOwner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

/**
 * 货主订单编号规则配置Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Api(tags = "货主订单编号规则管理")
@RestController
@RequestMapping("/wms/orderNumberRule")
public class WmsOwnerOrderNumberRuleController extends BaseController
{
    @Autowired
    private IWmsOwnerOrderNumberRuleService wmsOwnerOrderNumberRuleService;
    
    @Autowired
    private IWmsCargoOwnerService wmsCargoOwnerService;

    /**
     * 查询货主订单编号规则配置列表
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmsOwnerOrderNumberRule wmsOwnerOrderNumberRule)
    {
        startPage();
        List<WmsOwnerOrderNumberRule> list = wmsOwnerOrderNumberRuleService.selectWmsOwnerOrderNumberRuleList(wmsOwnerOrderNumberRule);
        return getDataTable(list);
    }

    /**
     * 根据货主ID查询订单编号规则配置列表
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:list')")
    @GetMapping("/listByOwnerId/{ownerId}")
    public AjaxResult listByOwnerId(@PathVariable("ownerId") Long ownerId)
    {
        List<WmsOwnerOrderNumberRule> list = wmsOwnerOrderNumberRuleService.selectRuleListByOwnerId(ownerId);
        return AjaxResult.success(list);
    }

    /**
     * 导出货主订单编号规则配置列表
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:export')")
    @Log(title = "货主订单编号规则配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsOwnerOrderNumberRule wmsOwnerOrderNumberRule)
    {
        List<WmsOwnerOrderNumberRule> list = wmsOwnerOrderNumberRuleService.selectWmsOwnerOrderNumberRuleList(wmsOwnerOrderNumberRule);
        ExcelUtil<WmsOwnerOrderNumberRule> util = new ExcelUtil<WmsOwnerOrderNumberRule>(WmsOwnerOrderNumberRule.class);
        util.exportExcel(response, list, "货主订单编号规则配置数据");
    }

    /**
     * 获取货主订单编号规则配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:query')")
    @GetMapping(value = "/{ruleId}")
    public AjaxResult getInfo(@PathVariable("ruleId") Long ruleId)
    {
        return AjaxResult.success(wmsOwnerOrderNumberRuleService.selectWmsOwnerOrderNumberRuleByRuleId(ruleId));
    }

    /**
     * 新增货主订单编号规则配置
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:add')")
    @Log(title = "货主订单编号规则配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsOwnerOrderNumberRule wmsOwnerOrderNumberRule)
    {
        // 从货主信息中获取租户ID
        if (wmsOwnerOrderNumberRule.getOwnerId() != null) {
            WmsCargoOwner cargoOwner = wmsCargoOwnerService.selectWmsCargoOwnerById(wmsOwnerOrderNumberRule.getOwnerId());
            if (cargoOwner != null && cargoOwner.getTenantId() != null) {
                wmsOwnerOrderNumberRule.setTenantId(String.valueOf(cargoOwner.getTenantId()));
            } else {
                wmsOwnerOrderNumberRule.setTenantId("000000"); // 默认租户ID
            }
        } else {
            wmsOwnerOrderNumberRule.setTenantId("000000"); // 默认租户ID
        }
        
        // 自动生成规则模板
        if (wmsOwnerOrderNumberRule.getRuleTemplate() == null || wmsOwnerOrderNumberRule.getRuleTemplate().trim().isEmpty()) {
            String ruleTemplate = generateRuleTemplate(wmsOwnerOrderNumberRule);
            wmsOwnerOrderNumberRule.setRuleTemplate(ruleTemplate);
        }
        
        return toAjax(wmsOwnerOrderNumberRuleService.insertWmsOwnerOrderNumberRule(wmsOwnerOrderNumberRule));
    }
    
    /**
     * 根据规则配置自动生成规则模板
     * 规则模板格式：{PREFIX}{SEPARATOR}{DATE}{SEPARATOR}{SERIAL}{SUFFIX}
     */
    private String generateRuleTemplate(WmsOwnerOrderNumberRule rule) {
        StringBuilder template = new StringBuilder();
        
        // 添加前缀
        if (rule.getPrefix() != null && !rule.getPrefix().trim().isEmpty()) {
            template.append("{PREFIX}");
        }
        
        // 添加分隔符（如果有前缀且有其他部分）
        String separator = rule.getDivision();
        boolean hasSeparator = separator != null && !separator.trim().isEmpty();
        
        // 添加日期
        if (rule.getDateFormat() != null && !rule.getDateFormat().trim().isEmpty()) {
            if (template.length() > 0 && hasSeparator) {
                template.append("{SEPARATOR}");
            }
            template.append("{DATE}");
        }
        
        // 添加流水号
        if (rule.getSerialLength() != null && rule.getSerialLength() > 0) {
            if (template.length() > 0 && hasSeparator) {
                template.append("{SEPARATOR}");
            }
            template.append("{SERIAL}");
        }
        
        // 添加后缀
        if (rule.getSuffix() != null && !rule.getSuffix().trim().isEmpty()) {
            if (template.length() > 0 && hasSeparator) {
                template.append("{SEPARATOR}");
            }
            template.append("{SUFFIX}");
        }
        
        // 如果模板为空，使用默认模板
        if (template.length() == 0) {
            template.append("{PREFIX}{SEPARATOR}{DATE}{SEPARATOR}{SERIAL}");
        }
        
        return template.toString();
    }

    /**
     * 修改货主订单编号规则配置
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:edit')")
    @Log(title = "货主订单编号规则配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsOwnerOrderNumberRule wmsOwnerOrderNumberRule)
    {
        return toAjax(wmsOwnerOrderNumberRuleService.updateWmsOwnerOrderNumberRule(wmsOwnerOrderNumberRule));
    }

    /**
     * 删除货主订单编号规则配置
     */
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:remove')")
    @Log(title = "货主订单编号规则配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ruleIds}")
    public AjaxResult remove(@PathVariable Long[] ruleIds)
    {
        return toAjax(wmsOwnerOrderNumberRuleService.deleteWmsOwnerOrderNumberRuleByRuleIds(ruleIds));
    }

    /**
     * 生成订单编号（供业务系统调用）
     * 
     * @param ownerId 货主ID
     * @param orderType 订单类型（RECEIPT-收货订单，PICKING-拣货订单，OUTBOUND-出库订单，TRANSFER-调拨订单，STOCKTAKING-盘点订单，RETURN-退货订单）
     * @return 生成的订单编号
     */
    @ApiOperation(value = "生成订单编号", notes = "根据货主ID和订单类型生成唯一的订单编号，供各业务功能调用")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ownerId", value = "货主ID", required = true, dataType = "Long", paramType = "path"),
        @ApiImplicitParam(name = "orderType", value = "订单类型", required = true, dataType = "String", paramType = "path", 
                         allowableValues = "RECEIPT,PICKING,OUTBOUND,TRANSFER,STOCKTAKING,RETURN")
    })
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:generate')")
    @PostMapping("/generate/{ownerId}/{orderType}")
    public AjaxResult generateOrderNumber(
            @ApiParam(value = "货主ID", required = true) @PathVariable("ownerId") Long ownerId, 
            @ApiParam(value = "订单类型", required = true) @PathVariable("orderType") String orderType)
    {
        try {
            String orderNumber = wmsOwnerOrderNumberRuleService.generateOrderNumber(ownerId, orderType);
            return AjaxResult.success("订单编号生成成功", orderNumber);
        } catch (Exception e) {
            return AjaxResult.error("订单编号生成失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量生成订单编号（供业务系统调用）
     * 
     * @param ownerId 货主ID
     * @param orderType 订单类型
     * @param count 生成数量（最大100个）
     * @return 生成的订单编号列表
     */
    @ApiOperation(value = "批量生成订单编号", notes = "一次性生成多个订单编号，提高批量业务处理效率")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ownerId", value = "货主ID", required = true, dataType = "Long", paramType = "path"),
        @ApiImplicitParam(name = "orderType", value = "订单类型", required = true, dataType = "String", paramType = "path",
                         allowableValues = "RECEIPT,PICKING,OUTBOUND,TRANSFER,STOCKTAKING,RETURN"),
        @ApiImplicitParam(name = "count", value = "生成数量(1-100)", required = true, dataType = "Integer", paramType = "path")
    })
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:generate')")
    @PostMapping("/generateBatch/{ownerId}/{orderType}/{count}")
    public AjaxResult generateBatchOrderNumbers(
            @ApiParam(value = "货主ID", required = true) @PathVariable("ownerId") Long ownerId,
            @ApiParam(value = "订单类型", required = true) @PathVariable("orderType") String orderType,
            @ApiParam(value = "生成数量", required = true) @PathVariable("count") Integer count)
    {
        try {
            // 限制批量生成数量
            if (count <= 0 || count > 100) {
                return AjaxResult.error("生成数量必须在1-100之间");
            }
            
            java.util.List<String> orderNumbers = new java.util.ArrayList<>();
            for (int i = 0; i < count; i++) {
                String orderNumber = wmsOwnerOrderNumberRuleService.generateOrderNumber(ownerId, orderType);
                orderNumbers.add(orderNumber);
            }
            
            return AjaxResult.success("批量生成订单编号成功", orderNumbers);
        } catch (Exception e) {
            return AjaxResult.error("批量生成订单编号失败：" + e.getMessage());
        }
    }
    
    /**
     * 验证订单编号格式（供业务系统调用）
     * 
     * @param ownerId 货主ID
     * @param orderType 订单类型
     * @param orderNumber 待验证的订单编号
     * @return 验证结果
     */
    @ApiOperation(value = "验证订单编号格式", notes = "验证给定的订单编号是否符合指定货主和订单类型的编号规则")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ownerId", value = "货主ID", required = true, dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "orderType", value = "订单类型", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "orderNumber", value = "待验证的订单编号", required = true, dataType = "String", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:validate')")
    @GetMapping("/validate")
    public AjaxResult validateOrderNumber(
            @ApiParam(value = "货主ID", required = true) @RequestParam("ownerId") Long ownerId,
            @ApiParam(value = "订单类型", required = true) @RequestParam("orderType") String orderType,
            @ApiParam(value = "待验证的订单编号", required = true) @RequestParam("orderNumber") String orderNumber)
    {
        try {
            boolean isValid = wmsOwnerOrderNumberRuleService.validateOrderNumber(ownerId, orderType, orderNumber);
            if (isValid) {
                return AjaxResult.success("订单编号格式验证通过", true);
            } else {
                return AjaxResult.success("订单编号格式验证失败", false);
            }
        } catch (Exception e) {
            return AjaxResult.error("订单编号验证失败：" + e.getMessage());
        }
    }

    /**
     * 预览订单编号格式
     * 
     * @param wmsOwnerOrderNumberRule 订单编号规则配置
     * @return 预览的订单编号
     */
    @ApiOperation(value = "预览订单编号格式", notes = "根据配置的规则预览生成的订单编号格式")
    @PreAuthorize("@ss.hasPermi('wms:orderNumberRule:preview')")
    @PostMapping("/preview")
    public AjaxResult previewOrderNumber(
            @ApiParam(value = "订单编号规则配置", required = true) @RequestBody WmsOwnerOrderNumberRule wmsOwnerOrderNumberRule)
    {
        try {
            String previewNumber = wmsOwnerOrderNumberRuleService.previewOrderNumber(wmsOwnerOrderNumberRule);
            return AjaxResult.success("预览成功", previewNumber);
        } catch (Exception e) {
            return AjaxResult.error("预览失败：" + e.getMessage());
        }
    }
}